package com.itheima.health.controller;

import com.itheima.health.common.GlobalConstart;
import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.itheima.health.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * C端验证码登陆
 *
 * @author zhiHaoD
 * @since 2022/11/22 15:11
 */
@Slf4j
@RestController
@RequestMapping("/mobile")
public class ValidateCodeController {

    @Autowired
    private MemberService memberService;

    /**
     * 发送验证码
     */
    @PostMapping("/validateCode/send")
    public Result send(String type, String telephone,HttpSession session){
        log.info("发送验证码==== >");
        //生成4个随机数
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        // 调用短信工具发送短信
        //SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", telephone, code);
        log.info("code==========> {}",code);
        // 写入到session
        session.setAttribute(telephone,code);
        // 验证码发送成功
        return new Result(true,MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

    /**
     * 手机验证码登录
     */

    @PostMapping("/login/smsLogin")
    public Result smsLogin(@RequestBody Map map, HttpSession session, HttpServletResponse response){
        log.info("验证登录==== >",map);
        // 1.获取手机号和验证码
        String telephone = map.get("telephone").toString();
        String newCode = map.get("validateCode").toString();
        // 2.从session中或获取手机号对应的正确验证码
        String oldCode = (String) session.getAttribute(telephone);
        // 3.进行验证码对比，如果不一致，直接返 回登录失败
        if (oldCode == null || !oldCode.equals(newCode)){
            // 验证码输入错误
            return new Result(false,MessageConst.VALIDATECODE_ERROR);
        }else {
            // 验证码正确
            // 判断当前用户是否为会员
            Member member =memberService.findByTelephone(telephone);
            if (member == null){
                // 当前用户不是会员，自动完成注册
                member = new Member();
                member.setPhoneNumber(telephone);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            // 登录成功
            // 写入Cookie，跟踪用户
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            // 路径
            cookie.setPath("/");
            // 有效期30天
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            // 保存会员信息session中
            session.setAttribute(MessageConst.USER_ID,member.getId());
            return new Result(true,MessageConst.LOGIN_SUCCESS,member);
        }
    }
}